package com.qf.myschool.servlet;

import com.qf.myschool.entity.Student;
import com.qf.myschool.service.IStudentService;
import com.qf.myschool.service.ITeacherService;
import com.qf.myschool.service.impl.StudentServiceImpl;
import com.qf.myschool.service.impl.TeacherServiceImpl;
import com.qf.myschool.vo.LoginUserVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 学生和老师公共的Servlet
 */
@WebServlet("/CommonServlet")
public class CommonServlet extends FatherServlet{
	private static final long serialVersionUID = 1L;

	//继承FatherServlet中service,service方法中根据请求方法反射对象调用方法

	/**
	*创建学生业务对象和老师业务对象
	*/
	IStudentService stuService=new StudentServiceImpl();
	ITeacherService teaService=new TeacherServiceImpl();

	/***
	 * 修改学生信息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private String updateStudent(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, IllegalAccessException, NoSuchFieldException, InstantiationException {
		/*1.接收请求中数据*/
		//调用公共Servlet中接收请求数据的方法,声明一个学生对象,用来接收请求中数据
		Student stu1=requestMap(Student.class,request,response);

		/*Student stu1=new Student();

		stu1.setName(request.getParameter("uname"));
		stu1.setCity(request.getParameter("city"));
		stu1.setEmail(request.getParameter("email"));
		stu1.setSex(request.getParameter("sex"));
		String[] hobbys=request.getParameterValues("hobby");
		stu1.setHobby(Arrays.toString(hobbys));*/
		
		/*2.选择相应业务层处理请求,并得到结果*/
		int result=stuService.modifyStudent(stu1);
		
		/*根据身份跳转页面*/
		if ("student".equals(((LoginUserVo)request.getSession().getAttribute("stu")).getRole())) {//学生
			//将提示存在请求对象中
			request.setAttribute("mess", "修改成功!");
			//转发,将请求和响应对象带到下一个页面
			return "index.jsp";
		} else {//老师修改成功后,跳转后查看所有学生信息的Servlet中
			return "redirect:TeacherServlet?method=allStudent";
		}
	}

	/**
	 * 修改用户密码
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private String modifyPwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
		/*1.获得请求中数据*/
		//获得当前用户信息
		LoginUserVo stu2=(LoginUserVo) request.getSession().getAttribute("stu");
		//获得新密码
		String newPwd=request.getParameter("newPwd");
		
		
		/*分身份role,调用相应业务层去修改密码,并接收结果*/
		//声明一个变量存修改的结果
		int result=0;
		if ("student".equals(stu2.getRole())) {//修改学生密码
			//用学生数据访问对象调用修改密码的方法
			result= stuService.modifyPwd(stu2.getName(),newPwd);
		} else {//修改老师密码
			//创建老师数据访问对象调用修改密码的方法
			result=teaService.modifyPwd(stu2.getName(),newPwd);
		}
		
		/*3.根据结果选择相应视频展示*/
		if (result>0) {//修改成功
			response.setContentType("text/html;charset=utf-8");
			return "redirect:login.jsp";
		} else {//修改失败
			return "redirect:modifyPwd.jsp";
		}
	}

	/**
	 * 根据姓名查询学生信息并跳转到修改学生信息页面
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private String getStudentByName(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//根据登录身份判断操作
		/*1.获得要修改的用户名*/
		String uname=null;
		if ("student".equals(((LoginUserVo)request.getSession().getAttribute("stu")).getRole())) {//学生
			 uname=((LoginUserVo)request.getSession().getAttribute("stu")).getName();
		} else {//老师
			uname=request.getParameter("uname");
		}
		
		/*2.调用业务层处理请求并接收结果*/
		Student stu3=stuService.queryStudentByUname(uname);
		
		/*3.根据结果跳转到相应页面*/
		//将用户的数据存到请求对象中
		request.setAttribute("stu4", stu3);
		//转发,将请求和响应对象带到下一个页面
		return "modifyUser.jsp";
	}

	/**
	 * 登录功能
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 * @throws ServletException
	 */
	private String login(HttpServletRequest request, HttpServletResponse response)
			throws IOException, UnsupportedEncodingException, ServletException, IllegalAccessException, NoSuchFieldException, InstantiationException {
		/*1.接收请求中数据*/
		//调用公共Servlet中接收请求的方法,创建登录模板对象,接收请求中数据
		LoginUserVo u1=requestMap(LoginUserVo.class,request,response);

		/*LoginUserVo u1 = new LoginUserVo();
		//用请求对象按表单项的Name属性接收value属性值,并存在学生对象的属性中
		u1.setName(request.getParameter("uname"));
		u1.setPassword(request.getParameter("pwd"));
		u1.setRole(request.getParameter("role"));*/
		//接收记住我的复选框的值
		String rememberMe = request.getParameter("rememberMe");

		//接收用户输入验证码
		String code = request.getParameter("code");
		//获得系统生成验证码(将session中提前存的系统的验证码获得)
		String checkCode = (String) request.getSession().getAttribute("checkCode");

		if (checkCode.equalsIgnoreCase(code)) {
			/*2.分身份处理调用相应业务层处理登录请求,并接收结果*/
			int result = 0;
			if ("student".equals(u1.getRole())) {//学生登录
				result = stuService.login(u1);

			} else if ("teacher".equals(u1.getRole())) {//老师登录
				result = teaService.login(u1);
			}

			/*3.根据登录的结果,选择相应页面跳转*/
			if (result == 0) {//登录失败
				//重定向
				return "redirect:login.jsp";
			} else {//登录成功
				//判断是否勾选记住我
				if ("on".equals(rememberMe)) {
					/*
					 cookie按key-value方式存值,key和value是String类型,
					 但是cookie中value只能存ASCII,也就是说只能存英文,数字不能存中文
					 如果想用cookie中value存中文,先将中文编码,客户端再解码
					 注意:编码和解码只对中文有用
					 */
					//用cookie记住用户信息
					Cookie c1 = new Cookie("uname1", URLEncoder.encode(u1.getName(), "utf-8"));
					Cookie c2 = new Cookie("pwd1", u1.getPassword());
					//设置cookie有效期
					c1.setMaxAge(60);
					c2.setMaxAge(60);

					//将cookie对象写入到客户端
					response.addCookie(c1);
					response.addCookie(c2);

				}

				/*登录成功后,要用session将用户信息存下来,以备后面功能使用*/
				request.getSession().setAttribute("stu", u1);

				//转发
				return "index.jsp";
			}
		} else {
			//设置响应内容类型
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().write("验证码有误!");
			//3秒跳转到登录页
			return "redirect:login.jsp";

		}
	}

	/**
	 * 注册/添加学生功能
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private String register(HttpServletRequest request, HttpServletResponse response) throws IOException, IllegalAccessException, NoSuchFieldException, InstantiationException {
		/*1.接收请求数据*/
		//调用公共servlet中方法,声明一个学生对象接收请求中数据
		Student stu1=requestMap(Student.class,request,response);
		//获得老师添加学生信息的标记
		String flag=request.getParameter("flag1");

		/*//声明一个学生对象,用来接收请求中数据
		Student stu1=new Student();
		stu1.setName(request.getParameter("uname"));
		stu1.setPassword(request.getParameter("pwd"));
		stu1.setCity(request.getParameter("city"));
		stu1.setEmail(request.getParameter("email"));
		stu1.setSex(request.getParameter("sex"));
		String[] hobbys=request.getParameterValues("hobby");
		//获得老师添加学生信息的标记
		String flag=request.getParameter("flag1");
		stu1.setHobby(Arrays.toString(hobbys));*/

		/*2.调用业务层处理请求,并接收返回的处理结果*/
		int result=stuService.register(stu1);


		/*3.根据结果选择相应页面跳转*/
		//第二种解决响应乱码:设置响应的内容类型及浏览器展示信息的编码方式
		response.setContentType("text/html;charset=utf-8");

		if (result>0) {
			//根据老师标记,确定跳转页面
			if ("".equals(flag)||flag==null) {//学生注册成功
				return "redirect:login.jsp";
			} else {//老师添加学生成功,跳转查看所有学生信息的servlet
				return "redirect:TeacherServlet?method=allStudent";
			}
		} else {
			response.getWriter().write("注册学生失败");
			//三秒跳转到注册页面
			return "redirect:register.jsp";
		}
	}

}
